package net.cityside.dp.tools.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {

  public static String loadFileAsString(File file) throws IOException {
    byte[] buffer = new byte[(int) file.length()];
    BufferedInputStream in = null;
    try {
      in = new BufferedInputStream(new FileInputStream(file));
      in.read(buffer);
    } finally {
      if (in != null) {
        // 还真会出null吗，当构造失败时
        in.close();
      }
    }
    return new String(buffer);
  }

  public static void saveToFile(String string, File file) throws IOException {
    saveToFile(string, file, null);
  }

  public static void saveToFile(String string, File file, String encoding) throws IOException {
    BufferedOutputStream out = null;
    try {
      out = new BufferedOutputStream(new FileOutputStream(file));
      if (encoding == null) {
        out.write(string.getBytes());
      } else {
        out.write(string.getBytes(encoding));
      }
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
}
